package com.example.exam.service.impl;

import com.example.exam.repository.QuestionAnswerRepository;
import com.example.exam.repository.UserRepository;
import com.example.exam.service.DataAnalysisService;
import com.example.exam.vo.WordCloud;
import com.huaban.analysis.jieba.JiebaSegmenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author shishuqian
 * date 2021/6/25
 * time 15:27
 **/
@Service
public class DataAnalysisServiceImpl implements DataAnalysisService {

    @Autowired
    private QuestionAnswerRepository questionAnswerRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<WordCloud> wordCloud(Integer id){
        List<String> answers = questionAnswerRepository.queryAllAnswerByQuestionId(id);
        //将得到的list集合拼接为StringBuffer对象
        StringBuilder word = new StringBuilder();
        for (String str: answers){
            word.append(",").append(str);
        }
        //jieba分词
        JiebaSegmenter jiebaSegmenter = new JiebaSegmenter();
        List<String> list = jiebaSegmenter.sentenceProcess(word.toString());
        //过滤长度小于2的字符串(因为这些大多数是标点符号，停用词等意义不大的字符串)
        list.removeIf(str -> str.length() < 2);
        //统计每个字符串出现的频率
        Map<String,Integer> map = new HashMap<>();
        for (String str:list){
            if (map.containsKey(str)){
                Integer count = map.get(str);
                count++;
                map.put(str,count);
            }else {
                map.put(str,1);
            }
        }
        List<WordCloud> clouds = new ArrayList<>();
        Set<Map.Entry<String, Integer>> set = map.entrySet();
        for (Map.Entry<String, Integer> next : set) {
            WordCloud cloud = new WordCloud(next.getKey(), next.getValue());
            clouds.add(cloud);
        }
        return clouds;
    }

    @Override
    public List<String> findNameDan(Integer questionId,String userAnswer) {
        List<Integer> ids = questionAnswerRepository.findNameDan(questionId, userAnswer);
        List<String> list =  new ArrayList<>();
        for (int id:ids){
            String realName = userRepository.findById(id).get().getRealName();
            list.add(realName);
        }
        return list;
    }

    @Override
    public List<String> findNameDuo(Integer questionId, String a, String b, String c, String d) {
        List<Integer> ids = questionAnswerRepository.findNameDuo(questionId, a, b, c, d);
        List<String> list =  new ArrayList<>();
        for (int id:ids){
            String realName = userRepository.findById(id).get().getRealName();
            list.add(realName);
        }
        return list;
    }
}
